var Monitor = {
  uid: null,
  startTime: null,
  pageInitInfo: {},
  sessionId: "",
  options: {
    // baseUrl: "http://localhost:3002/moitor_api",
    baseUrl: "https://conviviality.omnimkt.com/monitor/moitor_api",
    // baseUrl: "https://docker.omnimkt.com/monitor/moitor_api",
    // baseUrl: "http://117.72.38.43/monitor/moitor_api",
    // baseUrl: "https://monitor.menglingkai.xyz/monitor/moitor_api",
    appid: "wxf1ba6bbf4a70ac1c",
    unionid: "",
    openid: "",
    projectId: "13",
    projectName: "GEMO",
    api_key: "8cf6f1900e910eb86da80834c6cecb42b672cb42fb35804538b8640231ac",
    currentPageUrl: "", //当前小程序路径
    ad_id: "", //推广生成出来的
    url_link_id: "", //Url_Link 生成出来的
    short_link_id: "", //Short Link 生成出来的
    debug: false, //调试
  },
  params: {},
  init: function (options, isOn = true) {
    // console.log('init options: ', options);
    if (options.openid) {
      this.uid = options.openid;
    } else {
      this.uid = wx.getStorageSync("uid");
    }
    if (!this.uid) {
      this.uid = Math.random().toString(36).substr(2);
      wx.setStorageSync("uid", this.uid);
    }

    if (options.debug) {
      console.log("大数据调试开启");
    }

    this.options = Object.assign(this.options, options);

    if (this.options.ad_id) {
      this.eventAddAdmerics();
    }

    if (this.options.url_link_id) {
      this.eventAddUrlLinkMetrics();
    }

    if (this.options.short_link_id) {
      this.eventAddShortLinkMetrics();
    }

    wx.onError((error) => {
      console.log("error: ", error);
      this.sendEvent("/event/error", {
        message: error,
      });
    });

    if (isOn) {
      wx.onAppShow((result) => {
        // console.log('onAppShow result: ', result);
        this.recordPageView(result);

        // 记录用户来源
        this.recordReferrer(result, () => {
          setTimeout(() => {
            this.getAddress();
          }, 3000);
        });
      });
    } else {
      this.recordPageView(options);
      // 记录用户来源
      this.recordReferrer(options, () => {
        setTimeout(() => {
          this.getAddress();
        }, 3000);
      });

      setTimeout(() => {
        this.createSession();
      }, 1000);

      setTimeout(() => {
        this.recordPageChange(options);
      }, 2000);
    }

    wx.onAppHide(() => {
      var stayTime = Date.now();
      this.sendEvent("/event/stay", {
        stayTime: stayTime,
      });
    });
  },

  // 备选方案
  setStoreInit(params) {
    // console.log('params: ', params);
    if (params?.query?.ad_id) {
      this.options.ad_id = params.query.ad_id;
    }
    if (params?.query?.url_link_id) {
      this.options.url_link_id = params.query.url_link_id;
    }
    if (params?.query?.short_link_id) {
      this.options.short_link_id = params.query.short_link_id;
    }
    this.params = params;
  },

  getStoreInit(options) {
    this.init(Object.assign(this.options, this.params, options), false);
  },

  recordPageView: function (result) {
    this.pageInitInfo = result;
    // this.sendEvent ("/pv", {params:result.query,scene:'wx-'+result.scene});
  },

  recordPageChange: function (params) {
    this.sendEvent("/pv", {
      params,
      scene: "wx-" + this.pageInitInfo.scene,
    }).then((res) => {
      if (res.code === 200) {
      }
    });
  },

  // 事件点击 -- 废除
  clickEvent: function (data) {
    this.sendEvent("/event/scene", data);
  },

  // 页面浏览
  pageView: function (data) {
    setTimeout(() => {
      this.sendEvent("/event/pageView", data);
    }, 500);
  },

  // 页面点击
  pageClickEvent: function (data) {
    this.sendEvent("/event/pageClickEvent", data);
  },

  // 页面弹窗浏览
  pagePopupViews: function (data) {
    setTimeout(() => {
      this.sendEvent("/event/pagePopupViews", data);
    }, 500);
  },

  // 页面弹窗操作事件
  pagePopupClickEvents: function (data) {
    this.sendEvent("/event/pagePopupClickEvent", data);
  },

  // 获取地理位置
  getAddress: function (data) {
    this.sendEvent("/getIpAddress", data).then((ret) => {
      this.getDeviceInfo(ret);
    });
  },

  getDeviceInfo: function (ret) {
    // console.log('ret: ', ret);
    var deviceInfo = wx.getSystemInfoSync();

    if (ret.code === 200) {
      if (ret.data?.city) {
        this.sendEvent("/event/device", {
          ...deviceInfo,
          location: ret.data.city,
        });
      } else if (ret.data?.province) {
        this.sendEvent("/event/device", {
          ...deviceInfo,
          location: ret.data.province,
        });
      } else {
        this.sendEvent("/event/device", deviceInfo);
      }
    } else {
      this.sendEvent("/event/device", deviceInfo);
    }
  },

  // getIp:function (params) {
  //   wx.request({
  //     url: 'https://portal-mini-qua.vancleefarpels.cn/ip/getIpAddress',
  //     data:{},
  //     success:res=>{
  //       console.log('res: ', res);
  //       if(res.code)
  //     }
  //   })
  // },

  recordReferrer: function (result, cb) {
    this.sendEvent("/event/referrer", {
      referrer: result.referrerInfo.appId,
    }).then((res) => {
      if (res.code === 200) {
        cb && cb();
      }
    });
  },

  recordConversion: function (eventType, additionalData) {
    this.sendEvent("/event/conversion", {
      eventType: eventType,
      data: additionalData,
    });
  },
  createSession: async function (cb) {
    this.sendEvent("/event/createSession").then((res) => {
      if (res.code === 200) {
        this.sessionId = res.data.sessionId;
        cb && cb();
      }
    });
  },

  endSession: function () {
    this.sendEvent("/event/endSession", {
      sessionId: this.sessionId,
    }).then((res) => {
      this.sessionId = "";
    });
  },

  eventShare: function () {
    this.sendEvent("/event/share");
  },

  eventAddAdmerics: function () {
    this.sendEvent("/event/addAdMetrics");
  },

  eventAddUrlLinkMetrics: function () {
    this.sendEvent("/event/addUrlLinkMetrics");
  },

  eventAddShortLinkMetrics: function () {
    this.sendEvent("/event/addShortLinkMetrics");
  },

  sendEvent: function (url, data = {}) {
    if (this.options.debug) {
      console.log("Sending event:", url, data);
    }
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.options.baseUrl + url,
        method: "POST",
        header: {
          "Content-Type": "application/json",
          "x-api-key": this.options.api_key,
        },
        data: Object.assign(
          {
            uid: this.uid,
            openid: this.options.openid,
            unionid: this.options.unionid,
            pageUrl: getCurrentPageUrl(),
            projectId: this.options.projectId,
            projectName: this.options.projectName,
            sessionId: this.sessionId,
            ad_id: this.options.ad_id,
            url_link_id: this.options.url_link_id,
            short_link_id: this.options.short_link_id,
          },
          data
        ),
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          }
        },
        fail: (fail) => {
          reject(fail);
        },
      });
    });
  },
};

function getCurrentPageUrl() {
  const pages = getCurrentPages();
  if (pages.length === 0) {
    return "";
  }
  const currentPage = pages[pages.length - 1];
  const url = currentPage.route;
  return url;
}

module.exports = Monitor;
